using Microsoft.EntityFrameworkCore;
using UserManagement.Data;
using UserManagement.Models;
using UserManagement.Util;

namespace UserManagement.Services;
 
public class UserService : IUserService  // 继承接口 
{
    private readonly AppDbContext _context;
    public UserService(AppDbContext context) => _context = context;
 
    // 方法名添加 Async 后缀以符合异步命名规范 
    public async Task<List<UserDto>> GetAllUsersAsync() =>
        await _context.Users 
            .Select(u => new UserDto { Id = u.Id, Username = u.Username, Email = u.Email })
            .AsNoTracking()
            .ToListAsync();
 
    public async Task<UserDto?> GetUserAsync(int id) =>
        await _context.Users
            .AsNoTracking()
            .Where(u => u.Id == id)
            .Select(u => new UserDto { Id = u.Id, Username = u.Username, Email = u.Email })
            .FirstOrDefaultAsync()
            .ConfigureAwait(false);
 
    public async Task<User> AddUserAsync(User user)
    {
        user.Id = SnowflakeIdGenerator.CreateId();
        _context.Users.Add(user);
        await _context.SaveChangesAsync();
        return user;
    }
 
    public async Task UpdateUserAsync(int id, User user)
    {
        var existingUser = await _context.Users.FindAsync(id);
        if (existingUser != null)
        {
            existingUser.Username = user.Username;
            existingUser.Email = user.Email;
            await _context.SaveChangesAsync();
        }
    }
 
    public async Task DeleteUserAsync(int id)
    {
        var user = await _context.Users.FindAsync(id);
        if (user != null)
        {
            _context.Users.Remove(user);
            await _context.SaveChangesAsync();
        }
    }

    public async Task<bool> AddUsersAsync(List<User> users)
    {
        foreach (var user in users)
        {
            user.Id = SnowflakeIdGenerator.CreateId();
        }
        _context.Users.AddRange(users);
        var saveChangesAsync = await _context.SaveChangesAsync();
        return users.Count == saveChangesAsync;
    }
}